package com.qlyl.modules.information.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qlyl.common.api.vo.Result;
import com.qlyl.common.constant.CommonCheckStatus;
import com.qlyl.modules.information.entity.EthTransaction;
import com.qlyl.modules.information.mapper.EthTransactionMapper;
import com.qlyl.modules.information.service.IConsumersService;
import com.qlyl.modules.information.service.IEthTransactionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EthTransactionServiceImpl extends ServiceImpl<EthTransactionMapper, EthTransaction> implements IEthTransactionService {

    private final EthTransactionMapper ethTransactionMapper;
    private final IConsumersService consumersService;

    public Result add(EthTransaction ethTransaction) {
        int result = this.ethTransactionMapper.insert(ethTransaction);
        if (result > 0)
            return Result.ok("添加EthTransaction成功！");
        return Result.error("添加EthTransaction失败!");
    }

    public Result modifyStatusOnSuccess(String transactionHash) {
        EthTransaction ethTransaction = new EthTransaction();
        ethTransaction.setTransactionHash(transactionHash);
        ethTransaction.setStatus(1);
        ethTransaction.setSuccessTime(new Date());

        int result = this.ethTransactionMapper.updateById(ethTransaction);
        String comsumersId = this.ethTransactionMapper.selectById(transactionHash).getComsumsId();
        boolean flag  = consumersService.frozenBatchChcek(comsumersId, CommonCheckStatus.SUCCESS_CHAIN);
        if (result > 0 && flag)
            return Result.ok("修改EthTransaction状态为上链成功！");
        return Result.error("修改EthTransaction状态为上链失败!");
    }

    public IPage<EthTransaction> selectAndConsumers(Page<EthTransaction> page, String userId) {
        return ethTransactionMapper.selectAndConsumers(page, userId);
    }
}
